package com.data.hijack.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import org.apache.log4j.Logger;

/**
 * 
 * @author husq
 *
 */
public class PropertiesReader {
    private static final Logger logger = Logger.getLogger(PropertiesReader.class);
    private volatile Properties usersConfig;
    private volatile File file;

    private PropertiesReader() {}

    public void setFile(File file) {
        this.file = file;
    }

    private void load() {
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            if (usersConfig == null) {
                usersConfig = new Properties();
            }
            usersConfig.load(in);
        } catch (IOException ie) {
            try {
                logger.error("Loading file error:" + file.getPath(), ie);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static PropertiesReader newInstance() {
        return new PropertiesReader();
    }

    public Properties getProperties() {
        if (usersConfig == null) {
            load();
        }
        return usersConfig;
    }

    public String getValue(String key) {
        try {
            return (String)getProperties().get(key);
        } catch (Exception e) {
            logger.error("Fetch value by key " + key + " error : \n" + e);
        }
        return null;
    }

    public String getValue(String key, String defualt) {
        String value = getValue(key);
        if (value == null) {
            return defualt;
        }
        return value;
    }
}
